import whisper
import opencc
import time

from moviepy.editor import VideoFileClip

import os
import sys

import subprocess
from socketio import Client

import multiprocessing

sio = Client()
    # 发送消息给服务器
def send_message_to_server1(message):
    sio.emit('transformer_message', {'message': message}, namespace='/transformer_')

def run_client():
    # 连接到服务器，并指定命名空间为 '/transformer_'
    
    # 运行客户端
    sio.wait()



def delete_files_in_folder(folder_path):
    # 遍历文件夹中的所有文件
    for file_name in os.listdir(folder_path):
        # 构建文件的绝对路径
        file_path = os.path.join(folder_path, file_name)
        try:
            # 删除文件
            if os.path.isfile(file_path):
                os.remove(file_path)
            # 如果是文件夹，则递归删除文件夹中的文件
            elif os.path.isdir(file_path):
                delete_files_in_folder(file_path)
        except Exception as e:
            print("",end='')

def transformerVideoToAudio(video_path,
                            audio_path,
                            video_name,
                            video_tag):
    
    try:
        video = VideoFileClip(video_path)
        audio = video.audio
        audio.write_audiofile(audio_path)
        print("音频提取完成！")
    except Exception as e:
        print("提取音频时出错：", e)
    # 创建 Socket.IO 客户端
    time_1=time.time()
    
    
    print("音频转录中...")
    send_message_to_server1(10)
        
    text_path = "text/" + video_name + ".txt"
    time_path = "text/" + video_name + "_time.txt"
    json_path = "data/" + video_name + ".json"
    
    converter=opencc.OpenCC("t2s.json") 
    # 转录音频
    model = whisper.load_model("base")
    send_message_to_server1(20)
    result = model.transcribe(audio_path, word_timestamps=True, language="Chinese")
    
    send_message_to_server1(40)
    
    # 获取"segments"键对应的值
    with open (text_path,"w",encoding="utf-8") as f:
        result_text=result['text']
        result_text=converter.convert(result_text)
        f.write(result_text)
        print("音频转录完成!")
    time_2=time.time()
    print(f"音频转录总耗时：{time_2-time_1}秒")

    #打开一个.txt文件以写入"segments"的内容
    segments = result.get("segments")

    if segments is not None:
        with open(time_path, "w", encoding="utf-8") as txt_file:
            for segment in segments:
                start_time = segment.get("start")
                end_time = segment.get("end")
                text = segment.get("text")
                text=converter.convert(text)
                txt_file.write(f"start:{start_time} --> end:{end_time} {text}\n")
    else:
        print("segments键不存在于result字典中。")
        
    extract_path = "text/" + video_name + "_extract.txt"
    
    subprocess.run(["python", "cpu_api.py", "--param1", text_path, "--param2", time_path, "--param3", extract_path, "--param4", json_path])

    
    # 调用函数删除指定文件夹下的全部文件
    folder_path = r'temp'
    delete_files_in_folder(folder_path)
    print("处理完成！")
   

    
if __name__=="__main__":
    
    # 创建并启动新进程
    sio.connect('http://127.0.0.1:8090', namespaces=['/transformer_'])

    client_process = multiprocessing.Process(target=run_client)
    client_process.start()
    # 解析参数
    params = {}
    for i in range(1, len(sys.argv), 2):
        params[sys.argv[i]] = sys.argv[i+1]
        
    print(params['--param1'])
    print(params['--param2'])
    print(params['--param3'])
    print(params['--param4'])
  
    transformerVideoToAudio(params['--param1'], params['--param2'], params['--param3'], params['--param4'])

